//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package com.qst.crop.controller;

import com.qst.crop.entity.IOTDeviceMessage;
import com.qst.crop.service.IOTDeviceMessageService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Api(
        tags = {"IOT平台Token获取模块"}
)
@RestController
@RequestMapping({"/iotMessage"})
@CrossOrigin
public class IOTTokenController {
    private static String token = null;
    private static Date expirationTime = new Date();
    @Autowired
    RestTemplate restTemplate;
    @Autowired
    IOTDeviceMessageService service;

    public IOTTokenController() {
    }

    @ApiOperation("获取IOT平台的token")
    @GetMapping({"/getiottoken/{code}"})
    public String getToken(@PathVariable("code") String code) {
        if (token == null || expirationTime.after(new Date())) {
            IOTDeviceMessage message = this.service.getByCode(code);
            String url = "https://".concat(message.getIAMEndpoint()).concat("/v3/auth/tokens");
            String extraData = "{\n\t\"auth\":{\n\t\t\"identity\":{\n\t\t\t\"methods\":[\"password\"],\n\t\t\t\"password\":{\n\t\t\t\t\"user\":{\n\t\t\t\t\t\"name\":\"" + message.getIAMUserName() + "\",\n\t\t\t\t\t\"password\":\"" + message.getIAMPassword() + "\",\n\t\t\t\t\t\"domain\":{\n\t\t\t\t\t\t\"name\":\"" + message.getIAMDomainId() + "\"\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\t\"scope\":{\n\t\t\t\"project\":{\n\t\t\t\t\"name\": \"" + message.getRegion() + "\"\n\t\t\t}\n\t\t}\n\t}\n}";
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity<String> entity = new HttpEntity(extraData, headers);
            ResponseEntity<String> responseEntity = this.restTemplate.postForEntity(url, entity, String.class, new Object[0]);
            HttpHeaders responseHeaders = responseEntity.getHeaders();
            List<String> headerValues = responseHeaders.get("X-Subject-Token");
            if (headerValues != null && !headerValues.isEmpty()) {
                String contentType = (String)headerValues.get(0);
                token = contentType;
                Calendar calendar = Calendar.getInstance();
                calendar.add(6, 1);
                Date oneDayLater = calendar.getTime();
                expirationTime = oneDayLater;
            }
        }

        return token;
    }
}
